package com.example.guiguiapplicatio.fragment.followup;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.Record;
import com.example.guiguiapplicatio.databinding.FragmentNewFollowUpBinding;
import com.example.guiguiapplicatio.fragment.followup.adapter.NewFollowUpFragmentAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewFollowUpFragment extends Fragment {

    private FragmentNewFollowUpBinding binding;
    private NewFollowUpFragmentAdapter adapter;

    private Integer PARAM_PAGE_BEGIN = 0;
    private Integer PARAM_PAGE_SIZE = 10;
    private String PARAM_SEARCH_STRING = "";

    private Retrofit retrofit;
    private Api api;
    private static OkHttpClient client = null;
    List<Record> NOW_DATA_LIST = new ArrayList<>();
    private  NavController navController;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(getString(R.string.api))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding=FragmentNewFollowUpBinding.inflate(inflater,container,false);
        binding.newFlowUpList.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));
        navController=Navigation.findNavController(container);

         initDate();
         reflashAndLoad();
         setSearchBar();
         setSetUpWithoutNet();
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });

        return binding.getRoot();
    }

    private void setSetUpWithoutNet() {
        binding.setupWithoutNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle =new Bundle();
                Record record=new Record();
                record.setName("临时对象");
                bundle.putSerializable("Record",record);
                bundle.putBoolean("IS_WITHOUT_NET",true);
                navController.navigate(R.id.action_newFollowUpFragment_to_classifyFragment,bundle);
            }
        });
    }

    private void setSearchBar() {
        binding.removeTextBtn.setVisibility(View.GONE);
        binding.etSearchtext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    binding.removeTextBtn.setVisibility(View.GONE);
                }else {
                    binding.removeTextBtn.setVisibility(View.VISIBLE);
                }
            }
        });
        binding.removeTextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etSearchtext.setText("");
            }
        });

        binding.searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.etSearchtext.getText().equals("")){
                    Toast.makeText(getContext(), "请输入查询内容", Toast.LENGTH_LONG).show();
                }else {
                    PARAM_SEARCH_STRING= String.valueOf(binding.etSearchtext.getText());
                    PARAM_PAGE_BEGIN=0;
                    Call<ResponseBody<List<Record>>> call =api.searchNowServering(PARAM_PAGE_BEGIN,PARAM_PAGE_SIZE,PARAM_SEARCH_STRING);
                    call.clone().enqueue(new Callback<ResponseBody<List<Record>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<Record>>> call, Response<ResponseBody<List<Record>>> response) {
                            ResponseBody<List<Record>> responseBody=response.body();
                            if (responseBody!=null) {
                                NOW_DATA_LIST.clear();
                                for (int i = 0; i < responseBody.getData().size(); i++) {
                                    NOW_DATA_LIST.add(responseBody.getData().get(i));
                                }
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<Record>>> call, Throwable t) {
                            if(getContext()!=null){
                                Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                                PARAM_PAGE_BEGIN=0;
                            }
                        }
                    });
                }
            }
        });
    }

    private void reflashAndLoad() {
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                PARAM_PAGE_BEGIN=0;
                binding.refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                Call<ResponseBody<List<Record>>> call =api.searchNowServering(PARAM_PAGE_BEGIN,PARAM_PAGE_SIZE,PARAM_SEARCH_STRING);
                call.clone().enqueue(new Callback<ResponseBody<List<Record>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<Record>>> call, Response<ResponseBody<List<Record>>> response) {
                        ResponseBody<List<Record>> responseBody=response.body();
                        if (responseBody!=null) {
                            NOW_DATA_LIST.clear();
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA_LIST.add(responseBody.getData().get(i));
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<Record>>> call, Throwable t) {
                        binding.refreshLayout.finishRefresh(false);//传入false表示刷新失败
                        if (getContext()!=null){
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                            PARAM_PAGE_BEGIN=0;
                        }

                    }
                });


            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishLoadMore(1000);
                PARAM_PAGE_BEGIN=NOW_DATA_LIST.size();
                Call<ResponseBody<List<Record>>> call =api.searchNowServering(PARAM_PAGE_BEGIN,PARAM_PAGE_SIZE,PARAM_SEARCH_STRING);
                call.clone().enqueue(new Callback<ResponseBody<List<Record>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<Record>>> call, Response<ResponseBody<List<Record>>> response) {
                        ResponseBody<List<Record>> responseBody=response.body();
                        if (responseBody!=null) {
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA_LIST.add(responseBody.getData().get(i));
                            }
                            binding.refreshLayout.finishLoadMore(true);
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<Record>>> call, Throwable t) {

                        binding.refreshLayout.finishLoadMore(false);
                        if (getContext()!=null){
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                            PARAM_PAGE_BEGIN=0;
                        }
                    }
                });

            }
        });
    }

    private void initDate() {
        PARAM_PAGE_BEGIN=0;
        Call<ResponseBody<List<Record>>> call =api.searchNowServering(PARAM_PAGE_BEGIN,PARAM_PAGE_SIZE,PARAM_SEARCH_STRING);
        call.clone().enqueue(new Callback<ResponseBody<List<Record>>>() {
            @Override
            public void onResponse(Call<ResponseBody<List<Record>>> call, Response<ResponseBody<List<Record>>> response) {
                ResponseBody<List<Record>> responseBody=response.body();
                if (responseBody!=null) {
                    NOW_DATA_LIST.clear();
                    NOW_DATA_LIST = responseBody.getData();
                    adapter = new NewFollowUpFragmentAdapter(NOW_DATA_LIST);
                    binding.newFlowUpList.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<List<Record>>> call, Throwable t) {
                adapter = new NewFollowUpFragmentAdapter(NOW_DATA_LIST);
                binding.newFlowUpList.setAdapter(adapter);
                if(getContext()!=null){
                    Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                }
            }
        });


    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView=requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

}